//
//  AXFHomeViewController.m
//  AXFEightGroup
//
//  Created by ooops on 12/22/16.
//  Copyright © 2016 ya. All rights reserved.
//

#import "AXFHomeViewController.h"
#import "AXFDataModel.h"
#import "AXFDeliverAddressController.h"
#import "AXFHomeTitleView.h"
#import "WaterFlowLayout.h"
#import "WaterFlowCollectionViewCell.h"
#import "AXFSectionOneCollectionViewCell.h"
#import "AXFHomeTableViewManager.h"
#import "AXFIconView.h"
#import "AXFDetailViewController.h"
#import "AXFShoppingButtonView.h"
#import "AXFSearchViewController.h"
#import "AXFBrowserViewController.h"


@interface AXFHomeViewController ()<UIGestureRecognizerDelegate, XRCarouselViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,CAAnimationDelegate>
@property(nonatomic,strong)UILabel*locationLabel;
@property(nonatomic,weak)AXFHomeTitleView*titleView;

@property (nonatomic, strong) UICollectionView *collectionView;                                 /** collectionView */
@property (nonatomic, strong) UITableView *tableView;                                           /** 表格视图       */
@property (nonatomic, strong) id<UITableViewDelegate,UITableViewDataSource> homeManeger;        /** Home表格管理对象 */
@property (nonatomic, strong) XRCarouselView *carouselView;                                     /** 轮播图        */
@property (nonatomic, strong) NSMutableArray *cycleImageArray;                                  /** 轮播图片数组   */
@property (nonatomic, strong) NSMutableArray *cycleDescpArray;                                  /** 轮播图描述数组 */
@property (nonatomic, strong) NSMutableArray<AXFDataModel *> *iconsArray;                       /** 分类数据数组   */
@property (nonatomic, strong) NSArray<AXFDataModel *> *activitiesArray;                         /** 列表数据数组   */
@property (nonatomic, strong) NSMutableArray<AXFDataModel *> *collectionArray;                  /** collectionViewArray */

@end

@implementation AXFHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupCollectionView];
    [self setupNavigationBar];
    [self setupNotifications];
    [self loadDeliverAddressArray];
    self.carouselView = [[XRCarouselView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, ScrollViewHeight)];
    [self httpPostMethod];
}

/** data */
- (void)httpPostMethod {
    self.cycleImageArray = [NSMutableArray array];
    self.cycleDescpArray = [NSMutableArray array];
    self.collectionArray = [NSMutableArray array];
    [_ModelMgr focus:^(NSArray<AXFDataModel *> * _Nonnull focusModels) {
        [focusModels enumerateObjectsUsingBlock:^(AXFDataModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [_cycleImageArray addObject:obj.imgURL];
            [_cycleDescpArray addObject:obj.name];
        }];
        
        [self setupScrollView];
        
    }];
    
    /** 分类数据 */
    [_ModelMgr icons:^(NSArray<AXFDataModel *> * _Nonnull iconsModels) {
        //AXFLog(@"iconsModels = %@",iconsModels);
        [self setupIconView:iconsModels];
    }];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    NSBlockOperation *blockOp1 = [NSBlockOperation blockOperationWithBlock:^{
        /** 列表数据 */
        [_ModelMgr activities:^(NSArray<AXFDataModel *> * _Nullable models) {
            self.activitiesArray = models;
        }];
    }];
    
    NSBlockOperation *blockOp2 = [NSBlockOperation blockOperationWithBlock:^{
        /** 新鲜热卖 */
        [_ModelMgr firstSells:^(NSArray<AXFDataModel *> * _Nullable models) {
            self.collectionArray = self.activitiesArray.mutableCopy;
            [models enumerateObjectsUsingBlock:^(AXFDataModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [self.collectionArray addObject:models[idx]];
            }];
            [self.collectionView reloadData];
        }];
    }];
    [queue addOperation:blockOp1];
    [queue addOperation:blockOp2];
    [blockOp2 addDependency:blockOp1];
}



-(void)loadDeliverAddressArray
{
    [_ModelMgr myAdress:^(NSArray<AXFDataModel *> * _Nonnull myAdressModels) {
        
        [self handleDeliverAddressArray:(myAdressModels)];
    }];
}


-(void)handleDeliverAddressArray:(NSArray<AXFDataModel *> *)array
{
    NSString*string=array[0].address;
    string=[string sj_beforeString:@" "];
    _titleView.locationLabel.text=string;
    _titleView.locationLabel.hidden=NO;
}


-(void)setupNavigationBar
{
    UITapGestureRecognizer*tapGestureRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickedToSelectLocation:)];
    _titleView=[AXFHomeTitleView loadView];
    [_titleView addGestureRecognizer:tapGestureRecognizer];
    self.navigationItem.titleView=_titleView;
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:1.00 green:0.85 blue:0.00 alpha:1.00];
    UIButton*scanButton=[self buttonWithTitle:@"扫一扫" ImageName:@"icon_black_scancode"];
    [scanButton addTarget:self action:@selector(clickedScanButton:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:scanButton];
    
    UIButton*searchButton=[self buttonWithTitle:@"搜索" ImageName:@"icon_search"];
    [searchButton addTarget:self action:@selector(clickedSearchButton:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:searchButton];
}


-(UIButton*)buttonWithTitle:(NSString*)title ImageName:(NSString*)imageName
{
    UIButton*button=[[UIButton alloc]initWithFrame:CGRectZero];
    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.titleLabel.font=[UIFont systemFontOfSize:10];
    [button sizeToFit];
    CGSize imageSize=button.imageView.frame.size;
    CGSize titleSize=button.titleLabel.frame.size;
    button.titleEdgeInsets=UIEdgeInsetsMake(0, -imageSize.width, -imageSize.height-2, 0);
    button.imageEdgeInsets=UIEdgeInsetsMake(-titleSize.height-2, 0, 0, -titleSize.width);
    return button;
}

#pragma mark - 导航条右侧搜索按钮
-(void)clickedSearchButton:(UIBarButtonItem*)searchButton
{
    [self.navigationController pushViewController:[AXFSearchViewController new] animated:YES];
}

-(void)clickedScanButton:(UIBarButtonItem*)scanButton
{
    
}

-(void)clickedToSelectLocation:(UITapGestureRecognizer*)tapGestureRecognizer
{
    AXFDeliverAddressController*vc=[[AXFDeliverAddressController alloc]init];
    __weak typeof(self)weakSelf=self;
    [vc setSelectAddressBlock:^(AXFDataModel*dataModel)
    {
        __strong typeof(weakSelf) strongSelf=weakSelf;
        [strongSelf handleDeliverAddressArray:@[dataModel]];
    }];

    
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)setupCollectionView {
    WaterFlowLayout *waterFlowLayout = [WaterFlowLayout new];
    CGRect rect = CGRectMake(0, collectionY, SCREEN_WIDTH, SCREEN_HEIGHT);
    _collectionView = [[UICollectionView alloc] initWithFrame:rect collectionViewLayout:waterFlowLayout];
    _collectionView.contentInset = UIEdgeInsetsMake(0, 0, collectionY, 0);
    _collectionView.backgroundColor = [UIColor lightGrayColor];
    _collectionView.delegate = self;
    _collectionView.dataSource  = self;
    
    [_collectionView registerNib:[UINib nibWithNibName:@"WaterFlowCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"WaterFlowCollectionViewCell"];
    [_collectionView registerNib:[UINib nibWithNibName:@"AXFSectionOneCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"AXFSectionOneCollectionViewCell"];
    self.view = _collectionView;
    //
}

/** 配置轮播图参数 */
- (void)setupScrollView {
    _carouselView.imageArray = _cycleImageArray;
    _carouselView.describeArray = _cycleDescpArray;
    
    _carouselView.pagePosition = PositionBottomRight;
    _carouselView.delegate = self;
    _carouselView.time = 2;
    
    //设置分页控件的图片,不设置则为系统默认
    [_carouselView setPageImage:[UIImage imageNamed:@"other"] andCurrentPageImage:[UIImage imageNamed:@"current"]];
    
    [self.view addSubview:_carouselView];
}

- (void)setupIconView:(NSArray<AXFDataModel *> *)model {
    //CGRectMake(0, ScrollViewHeight, SCREEN_WIDTH, IconViewHeight)
    AXFIconView *iconView = [[AXFIconView alloc] initWithFrame:CGRectMake(0, ScrollViewHeight, SCREEN_WIDTH, IconViewHeight) model:model];
    [self.view addSubview:iconView];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //清除缓存
    [XRCarouselView clearDiskCache];
    
}

#pragma mark XRCarouselViewDelegate
- (void)carouselView:(XRCarouselView *)carouselView clickImageAtIndex:(NSInteger)index {
    NSLog(@"点击了第%ld张图片", (long)index);
}


#pragma mark - UICollectionView DataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.collectionArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // = [collectionView dequeueReusableCellWithReuseIdentifier:@"WaterFlowCollectionViewCell" forIndexPath:indexPath];
    AXFDataModel *tempModel = self.collectionArray[indexPath.item];
    if(indexPath.item <= 3) {
        AXFSectionOneCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AXFSectionOneCollectionViewCell" forIndexPath:indexPath];
        cell.model = tempModel;
        return cell;
        
    } else {
        WaterFlowCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WaterFlowCollectionViewCell" forIndexPath:indexPath];
        cell.model = tempModel;
        return cell;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.item > 3) {
        AXFDetailViewController *detailView = [AXFDetailViewController new];
        if (self.navigationController) {
            detailView.model = self.collectionArray[indexPath.item];
            [self.navigationController pushViewController:detailView animated:YES];
        }
    } else {
        AXFBrowserViewController *browser = [AXFBrowserViewController new];
        browser.jumpURL = [NSURL URLWithString:self.activitiesArray[indexPath.item].customURL];
        [self.navigationController pushViewController:browser animated:YES];
    }
}

#pragma mark - 配置监听购物车按钮操作通知
- (void)setupNotifications {
    //id observer,  SEL sel, NSString *key
    NotificationCenterAddObserver(self, Action_AXFShoppingButtonView_Plus, @selector(plusClickedNotification:));
    NotificationCenterAddObserver(self, Action_AXFShoppingButtonView_Miuns, @selector(minusClickedNotification:));
    NotificationCenterAddObserver(self, Action_AXFShoppingButtonView_AmountChange, @selector(amountChange:));
}

///增加逻辑
- (void)plusClickedNotification:(NSNotification *)notification {
//    WaterFlowCollectionViewCell *cell = [self productCellWithShoppingButtonnotification:notification];
    [self animationForNotification:notification];
}
//减少逻辑
- (void)minusClickedNotification:(NSNotification *)notification {
//    WaterFlowCollectionViewCell *cell = [self productCellWithShoppingButtonnotification:notification];
    
}
//返回对应的cell
- (WaterFlowCollectionViewCell *)productCellWithShoppingButtonnotification:(NSNotification *)notification {
    if ( ![notification.object isKindOfClass:[WaterFlowCollectionViewCell class]] ) {
        return nil;
    }
    WaterFlowCollectionViewCell *cell = notification.object;
    return cell;
}
//购物车数量变化逻辑
- (void)amountChange:(NSNotification *)notification {
    //NSLog(@"总数量 = %ld",_ModelMgr.productTotalAmount);
    NSInteger totalAmont = _ModelMgr.productTotalAmount;
    self.tabBarController.tabBar.items[2].badgeValue = totalAmont > 0 ? [NSString stringWithFormat:@"%ld",_ModelMgr.productTotalAmount] : nil;
}
//按钮动画
- (void)animationForNotification:(NSNotification *)notification{
    WaterFlowCollectionViewCell *cell = [self productCellWithShoppingButtonnotification:notification];
    CGPoint Point = [cell convertPoint:cell.productImageView.center toView:[UIApplication sharedApplication].keyWindow];
    CGRect Bounds = [cell convertRect:cell.productImageView.bounds toView:[UIApplication sharedApplication].keyWindow];
    CGRect StartRect = CGRectMake(Point.x, Point.y, Bounds.size.width, Bounds.size.height);
    CGPoint endPoint = CGPointMake(230, SCREEN_HEIGHT - 20);
    UIImageView *animationImage = [[UIImageView alloc] initWithImage:cell.productImageView.image];
    
    //购物车抖动
    UIView *shopTabBarItem = [self.tabBarController.tabBar subviews][3];
    //UIImageView *imgV = [self.tabBarController.tabBar subviews][3].subviews;
    [[PurchaseCarAnimationTool shareTool] startAnimationandView:animationImage andRect:StartRect andFinisnRect:endPoint andFinishBlock:^(BOOL finish) {
        [PurchaseCarAnimationTool shakeAnimation:shopTabBarItem];
    }];
}


@end
